<?php
/**
 * ComProductSkusDao.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/10/27- 11:08 上午
 */

namespace common\dao;


use common\exception\ValidatorException;
use common\library\BaseDao;
use common\models\com\ComProductsSkus;
use common\models\es\EsComProductsSkus;
use Yii;
class ComProductSkusDao extends BaseDao
{


    /**
     * 写入sku表信息
     * @param array $data
     * @return ComProductsSkus
     * @throws ValidatorException
     */
    public function saveData(array $data)
    {
        $skus = new ComProductsSkus();

        $skus->load($data,'');

        if (!$skus->validate()) {
            throw new ValidatorException($skus->errorsToString());
        }

        if($skus->save())
        {
            return $skus;
        }else{
            throw new ValidatorException($skus->errorsToOneString());
        }
    }


    /**
     * 批量写入
     * @param array $batchData
     * @return int
     * @throws \yii\db\Exception
     */
    public function insetBatch(array $batchData)
    {

        $fields = array_keys($batchData[0]);
        return Yii::$app->db->createCommand()->batchInsert(ComProductsSkus::tableName(),$fields,$batchData)->execute();
    }

    /**
     * 批量更新sku
     * @param $productId
     * @return int
     * @throws \yii\db\Exception
     */
    public function updateBatch($productId,array $batchData)
    {
        //ComProductsSkus::deleteAll(['product_id'=>$productId]);
        //$fields = array_keys($batchData[0]);
        //同步到es
        $es = new EsComProductsSkus();
        $attributes = $es->attributes();
        $es->syncDataSkuDelete($productId);
        //$ret =  Yii::$app->db->createCommand()->batchInsert(ComProductsSkus::tableName(),$fields,$batchData)->execute();
        $products = [];
        $models = ComProductsSkus::find()->where(['product_id' => $productId])->all();
        foreach ($models as $model) {
            $product = [];
            foreach ($attributes as $column) {
                $product[$column] = $model->$column;
            }
            $products[] = $product;
        }
        $res = $products ? $es->syncDataSku($products) : [];
        return $res;

    }





}
